<?php


namespace app\admin\controller\Goods;


use app\admin\controller\BaseController;
use app\admin\model\Goods\GoodsCateModel;
use app\admin\model\Goods\GoodsCateRelationModel;
use app\Utils\ImageUtil;
use app\Utils\Util;
use think\facade\Db;
use think\Request;

class GoodsCate extends BaseController
{
    /**
     * 分页查询
     * @param Request $request
     * @return array
     */
    public function getGoodsCateList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $page = $param['page'];
        $limit = $param['limit'];
        $cate_name = !empty($param['cate_name']) ? $param['cate_name'] : "";
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        $is_del = !empty($param['is_del']) ? $param['is_del'] : "";
        if (empty($page)) {
            $page = 1;
        }
        if (empty($limit)) {
            $limit = 10;
        }

        if (!empty($cate_name)) {
            array_push($where, ['type_name', 'like', '%' . $cate_name . '%']);
        }
        if (!empty($is_show)) {
            if ($is_show == 1) {
                array_push($where, ['is_show', '=', 1]);
            }
            if ($is_show == 2) {
                array_push($where, ['is_show', '=', 0]);
            }
        }
        if (!empty($is_del)) {
            if ($is_del == 1) {
                array_push($where, ['is_del', '=', 0]);
            }
            if ($is_del == 2) {
                array_push($where, ['is_del', '=', 1]);
            }
        }
        $list = GoodsCateModel::getGoodsCateListWhere($page, $limit, $where);
        $count = GoodsCateModel::getGoodsCateCountWhere($where);
        foreach ($list as &$item){
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
        }
        unset($item);

        return Util::returnPageJson(self::CODE_DATA, $count, $list, "");
    }


    /**
     * 一级节点
     * @param Request $request
     * @return array
     */
    public function getNodeCate(Request $request)
    {
        $list = GoodsCateModel::getGoodsCateWhereMore([['pid', '=', 0], ['is_show', '=', 1], ['is_del', '=', 0]]);
        return Util::returnJson(self::CODE_SUCCESS, $list, "");
    }

    /**
     * 添加
     * @param Request $request
     * @return array
     */
    public function addGoodsCate(Request $request)
    {
        $param = $request->param();
        $cate_name = $param['cate_name'];
        $pid = !empty($param['pid']) ? $param['pid'] : 0;
        $sort = !empty($param['sort']) ? $param['sort'] : 0;
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        $data = [
            'cate_name' => $cate_name,
            'pid' => $pid,
            'sort' => $sort,
            'add_time' => date("Y-m-d H:i:s",time())
        ];

        //图片上传
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "goods/cate/" . date("Ymd") . '/';
            $url = ImageUtil::i()->upload($file, $path);
            $data['img'] = $url;
        }
        if (!empty($is_show) && $is_show == "on") {
            $data['is_show'] = 1;
        }
        $id = GoodsCateModel::addGoodsCate($data);
        if ($id) {
            return Util::returnJson(self::CODE_SUCCESS, $id, "添加成功");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "添加失败");
        }
    }

    /**
     * 更新
     * @param Request $request
     * @return array
     */
    public function editGoodsCate(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        $cate_name = !empty($param['cate_name']) ? $param['cate_name'] : "";
        $pid = !empty($param['pid']) ? $param['pid'] : 0;
        $sort = !empty($param['sort']) ? $param['sort'] : 0;
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        if (empty($id)) {
            return Util::returnJson(self::CODE_ERROR, null, "参数错误");
        }

        //图片上传
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "goods/cate/" . date("Ymd") . '/';
            $url = ImageUtil::i()->upload($file, $path);
        }

        if (!empty($url)) {
            $save['img'] = $url;
        }
        if (!empty($cate_name)) {
            $save['cate_name'] = $cate_name;
        }
        if (!empty($sort)) {
            $save['sort'] = $sort;
        }
        if (!empty($pid)) {
            $save['pid'] = $pid;
        } else {
            if (isset($pid) && $pid == 0) {
                $save['pid'] = $pid;
            }
        }
        if (!empty($is_show)) {
            if ($is_show == "on") {
                $save['is_show'] = 1;
            } else {
                $save['is_show'] = 0;
            }
        }else{
            $save['is_show'] = 0;
        }
        $flag = GoodsCateModel::updateGoodsCateWhere([['id', '=', $id]], $save);
        if ($flag) {
            return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "修改失败");
        }
    }

    /**
     * 删除
     * @param Request $request
     * @return array
     */
    public function delGoodsCate(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        //开启事务
        Db::startTrans();
        try {
            //中间逻辑代码
            $flag = GoodsCateModel::updateGoodsCateWhere([['id', '=', $id]], ['is_del' => 1]);
            if ($flag) {
                $relations = GoodsCateRelationModel::getGoodsCateRelationCountWhere([['cate_id', '=', $id]]);
                if ($relations) {
                    $flag = GoodsCateRelationModel::delGoodsCateRelationWhere([['cate_id', '=', $id]]);
                    if ($flag) {
                        //提交事务
                        DB::commit();
                        return Util::returnJson(self::CODE_SUCCESS, null, "删除成功");
                    } else {
                        DB::rollBack();
                        return Util::returnJson(self::CODE_ERROR, null, "删除失败4");
                    }
                } else {
                    DB::commit();
                    return Util::returnJson(self::CODE_SUCCESS, null, "删除成功3");
                }
            } else {
                DB::rollBack();
                return Util::returnJson(self::CODE_ERROR, null, "删除失败2");
            }
        } catch (\Exception $e) {
            //接收异常处理并回滚
            //回滚事务
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, $e, "删除失败1");
        }
    }


    /**
     * 获取可使用分类
     * @param Request $request
     * @return array
     */
    public function getCateAll(Request $request)
    {
        $param = $request->param();
        $cate_ids = [];
        $cates = GoodsCateModel::getGoodsCateWhereMore([['is_show','=',1]]);
        if(!empty($param['goods_id'])){
            $list = GoodsCateRelationModel::getGoodsCateRelationWhereMore([['goods_id','=',$param['goods_id']]]);
            if(!empty($list)){
                $cate_ids = [];
                foreach ($list as $item){
                    array_push($cate_ids,$item['cate_id']);
                }
            }
        }
        $data = [];
        foreach ($cates as $item){
            $arr['name'] = $item['cate_name'];
            $arr['value'] = $item['id'];
            if(!empty($cate_ids)){
                if(in_array($item['id'],$cate_ids)){
                    $arr['selected'] = true;
                }else{
                    $arr['selected'] = false;
                }
            }else{
                $arr['selected'] = false;
            }
            array_push($data,$arr);
        }
        return Util::returnJson(self::CODE_SUCCESS,$data,"");
    }

}
